package com.wandian.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @date : 2012-9-24, 14:18:31
 * @author: long
 */
public class Config {

    private static Properties properties = null;

    public static boolean initConfig(String path) {
        if ((path == null) || (path.equals(""))) {
            return false;
        }
        if (properties == null) {
            return loadProperties(path);
        }
        return true;
    }

    private static boolean loadProperties(String path) {
//    	System.out.println("Ready to load file:"+path);
        try {
            properties = new Properties();
            InputStream inputStream = new BufferedInputStream(new FileInputStream(path));
            properties.load(inputStream);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println(path);
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(path);
        }
        return false;
    }

    public static String getValue(String key) {
        if (properties == null) {
            return null;
        }
        return properties.getProperty(key);
    }

    public static int getInt(String key) {
        if (properties == null) {
            return 0;
        }
        String value = properties.getProperty(key);
        if (SplitUtil.isNumeric(value)) {
            return Integer.parseInt(value);
        }
        return 0;
    }

    public static String parseGlobalConfig(String configPath) {
        File configFile = new File(configPath);
        if (!configFile.exists()) {
            Log.error("Can not found config file, server start failed.");
            return null;
        }

        File gatewayConfig = new File(configFile.getParent(), "global_config.xml");
        if (!gatewayConfig.exists()) {
            Log.error("Can not found gateway config file, server start failed.");
            return null;
        }
        return gatewayConfig.getAbsolutePath();
    }
}